Go Language dictionary of map Usage Example analysis [Create fill traverse find modify delete]

  • 2020-06-07 04:37:07
  • OfStack

This article illustrates the use of Go language dictionary (map). To share for your reference, specific as follows:

A dictionary is a built-in data structure that holds an unordered collection of key-value pairs.

(1) Creation of a dictionary

1) make(map[KeyType]ValueType, initialCapacity)
2) make(map[KeyType]ValueType)
3) map[KeyType]ValueType{}
4) map[KeyType]ValueType{key1 : value1, key2 : value2, ... , keyN : valueN}

The difference between the first and the second is that the initial capacity is not specified, but you don't have to worry about this when you use it, because the nature of map is that once you run out of capacity, it automatically expands:

func test1() {
    map1 := make(map[string]string, 5)
    map2 := make(map[string]string)
    map3 := map[string]string{}
    map4 := map[string]string{"a": "1", "b": "2", "c": "3"}
    fmt.Println(map1, map2, map3, map4)
}

Output:


map[] map[] map[] map[c:3 a:1 b:2]

(2) Dictionary filling and traversal: for range

func test2() {
    map1 := make(map[string]string)
    map1["a"] = "1"
    map1["b"] = "2"
    map1["c"] = "3"
    for key, value := range map1 {
        fmt.Printf("%s->%-10s", key, value)
    }
}

As above, array padding is used map[key] = value When you walk through the dictionary, each entry returns two values, the key and the value. The results are as follows:


a->1   b->2   c->3

(3) Dictionary search, modification and deletion: delete()

func test3() {
    map4 := map[string]string{"a": "1", "b": "2", "c": "3"}
    val, exist := map4["a"]
    val2, exist2 := map4["d"]
    fmt.Printf("%v,%v\n", exist, val)
    fmt.Printf("%v,%v\n", exist2, val2)
    map4["a"] = "8" // Is there no difference between modifying a dictionary and adding a dictionary
    fmt.Printf("%v\n", map4)
    fmt.Println(" delete b : ")
    delete(map4, "b")
    fmt.Printf("%v", map4)
}

When map specifies that key takes the corresponding value, it can be specified that two values are returned, the first is the corresponding value, and the second is the corresponding bool, indicating whether there is a value. As mentioned, "a" is definitely worth something and "b" is definitely not.

There is no difference between modifying a dictionary and adding a dictionary. If the specified key does not exist, it is created; otherwise, it is modified.

Deletion is the built-in function using go delete() , the output is as follows:


true,1
false,
map[a:8 b:2 c:3]
 delete b : 
map[a:8 c:3]

To access the dictionary, it is safer to:

map4 := map[string]string{"a": "1", "b": "2", "c": "3"}
val, exist := map4["d"]
if exist {
    fmt.Println(val)
} else {
    fmt.Println("not exists")
}

I hope this article has been helpful to you in Go programming.


Related articles: